﻿﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新题材</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        :root {
            --card-bg: #1A1512;
            --card-hover: #242424;
            --card-active: #2A2A2A;
        }

        html, body {
            height: 100%;
            margin: 0;
            overflow: hidden;
            background-color: #000000;
            color: #ffffff;
            font-size: 14px;
        }

        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        ::-webkit-scrollbar-track {
            background: #000000;
        }

        ::-webkit-scrollbar-thumb {
            background: #333333;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #444444;
        }

        .container-wrapper {
            display: flex;
            height: 100vh;
            overflow: hidden;
            background-color: #000000;
            padding-top: 0;
        }

        .left-panel {
            width: 50%;
            height: 100%;
            overflow-y: auto;
            padding: 0.25rem;
        }

        .right-panel {
            width: 50%;
            height: 100%;
            overflow-y: auto;
            border-left: 1px solid #333333;
            padding: 0.25rem;
        }

        .theme-card {
            background-color: var(--card-bg);
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 6px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 13px;
        }

        .theme-card:hover {
            background-color: var(--card-hover);
        }

        .theme-card.active {
            background-color: var(--card-active);
        }

        .date-divider {
            margin: 12px 0 8px 0;
            color: #E5E7EB;
            font-size: 12px;
        }

        .percentage {
            float: right;
            padding: 1px 6px;
            border-radius: 3px;
            font-size: 11px;
            color: white;
        }

        .percentage.up {
            background-color: #FF4D4F;
        }

        .percentage.down {
            background-color: #52C41A;
        }

        .stock-card {
            background-color: var(--card-bg);
            border-radius: 6px;
            padding: 6px;
            margin-bottom: 4px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 13px;
        }

        .stock-card:hover {
            background-color: var(--card-hover);
        }

        .header-section {
            position: sticky;
            top: 0;
            background-color: #000000;
            padding: 0.25rem 0;
            margin-bottom: 0.25rem;
            z-index: 10;
        }
        
        .header-section h3 {
            margin: 0; /* 移除标题的默认外边距 */
            padding: 0; /* 移除标题的默认内边距 */
        }
        
        .collect-button {
            background-color: #ffcc00;
            color: #1a1a1a;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            padding: 4px 8px;
            margin-left: 8px;
        }

        .collect-button:hover {
            background-color: red !important;
            color: #ffcc00;
        }
        
        .theme-title {
            background-color: #ffcc00;
            color: #1a1a1a;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: bold;
            margin-bottom: 6px;
            display: inline-block;
        }
        
        .text-xl {
            font-size: 16px;
        }
        
        .text-sm {
            font-size: 12px;
        }
        
        .font-medium {
            font-weight: 500;
        }
        
        .mt-1 {
            margin-top: 0.25rem;
        }
        
        .mt-2 {
            margin-top: 0.25rem;
        }
        
        .ml-2 {
            margin-left: 0.375rem;
        }
    </style>
</head>
<body>
    <div class="container-wrapper">
        <!-- 左侧主题列表 -->
        <div id="themeList" class="left-panel"></div>
        
        <!-- 右侧股票详情 -->
        <div class="right-panel">
            <div class="header-section">
                <div class="flex justify-between items-center">
                    <h3 id="detailTitle" class="text-xl font-bold text-white">请选择左侧主题查看详情</h3>
                    <button id="collectStocksBtn" class="collect-button">加入板块</button>
                </div>
            </div>
            <div id="stockList" class="space-y-2"></div>
        </div>
    </div>

    <script>
        let activeTheme = null;

        async function fetchThemeData() {
            try {
                const response = await fetch('https://prx.upchina.com/json/specialTheme/getTSDataNewThemeByDate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8',
                    },
                    body: JSON.stringify({
                        "stReq": {
                            "uiStart": 0,
                            "uiCount": 50
                        }
                    })
                });
                const data = await response.json();
                return data.stRsp.vThemeData;
            } catch (error) {
                console.error('Error fetching theme data:', error);
                return [];
            }
        }

        async function fetchStockDetails(plateCode) {
            try {
                const response = await fetch('https://gateway.upchina.com/json/stockextweb/stockExtDetail', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8',
                    },
                    body: JSON.stringify({
                        "stReq": {
                            "stHeader": {
                                "sSource": "题材宝-common/service/clue/getStockExtDetail"
                            },
                            "lDate": 0,
                            "iType": 6,
                            "iId": 0,
                            "iExt": 0,
                            "sExt": plateCode,
                            "vFilterType": [],
                            "vStock": [],
                            "eColumn": 4,
                            "eSort": 2,
                            "iStart": 0,
                            "iSize": 1150,
                            "bFromCache": true,
                            "stFrom": {},
                            "vBitmap": [28,64,0,0,0,0,68,254,248,32,0,0,0,48],
                            "mapIncFlag": {},
                            "mapReq": {},
                            "bDetail": false,
                            "iReqType": 1
                        }
                    })
                });
                const data = await response.json();
                return data.stRsp.vDataSimple || [];
            } catch (error) {
                console.error('Error fetching stock details:', error);
                return [];
            }
        }

        function formatDate(dateStr) {
            const year = dateStr.toString().substring(0, 4);
            const month = dateStr.toString().substring(4, 6);
            const day = dateStr.toString().substring(6, 8);
            return `${year}/${month}/${day}`;
        }

        function isToday(dateStr) {
            const today = new Date();
            const year = parseInt(dateStr.toString().substring(0, 4));
            const month = parseInt(dateStr.toString().substring(4, 6)) - 1;
            const day = parseInt(dateStr.toString().substring(6, 8));
            const date = new Date(year, month, day);
            
            return today.getFullYear() === year && 
                   today.getMonth() === month && 
                   today.getDate() === day;
        }

        async function showStockDetails(theme) {
            const detailTitle = document.getElementById('detailTitle');
            const stockList = document.getElementById('stockList');
            
            stockList.innerHTML = '<div class="text-center text-gray-300">加载中...</div>';

            const stocks = await fetchStockDetails(theme.sPlateCode);
            
            detailTitle.innerHTML = `
                <div class="flex items-center justify-between">
                    <span class="font-medium text-white">${theme.sPlateName}</span>
                    <span class="text-sm text-gray-300">共 ${stocks.length} 只股票</span>
                </div>
            `;
            
            stockList.innerHTML = `
                <div class="space-y-2">
                    ${stocks.map(stock => {
                        const percentage = stock.m1['4'] || 0;
                        const isUp = percentage > 0;
                        
                        return `
                            <div class="stock-card stock-item" data-code="${stock.code}">
                                <div class="flex justify-between items-center">
                                    <div>
                                        <span class="font-medium text-white">${stock.name}</span>
                                        <span class="text-gray-300 text-sm ml-2 stock-code">${stock.code}</span>
                                    </div>
                                    <span class="percentage ${isUp ? 'up' : 'down'}">
                                        ${isUp ? '+' : ''}${percentage.toFixed(2)}%
                                    </span>
                                </div>
                                <div class="text-sm text-gray-300 mt-2">
                                    ${stock.m2['49'][1] || '暂无业绩预告'}
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            `;

            stockList.querySelectorAll('.stock-card').forEach(card => {
                card.addEventListener('click', () => {
                    const code = card.dataset.code;
                    window.location.href = `http://www.treeid/code_${code}`;
                });
            });
        }

        function createThemeCard(theme) {
            const card = document.createElement('div');
            card.className = 'theme-card';
            if (activeTheme === theme.sPlateCode) {
                card.classList.add('active');
            }

            card.innerHTML = `
                <div>
                    <div class="theme-title font-medium text-white">
                        ${theme.sPlateName}
                    </div>
                    <div class="text-gray-300 text-sm mt-1">
                        ${theme.parentName}
                    </div>
                    <div class="text-gray-300 text-sm mt-2">
                        投资逻辑：${theme.driveLogic}
                    </div>
                </div>
            `;

            card.addEventListener('click', async () => {
                document.querySelectorAll('.theme-card').forEach(c => c.classList.remove('active'));
                card.classList.add('active');
                activeTheme = theme.sPlateCode;
                await showStockDetails(theme);
            });

            return card;
        }

        async function renderThemeList() {
            const themeList = document.getElementById('themeList');
            const themes = await fetchThemeData();
            
            let currentDate = null;
            themeList.innerHTML = '';
            
            themes.forEach((theme, index) => {
                const dateStr = formatDate(theme.effectiveTime);
                
                if (currentDate !== dateStr) {
                    currentDate = dateStr;
                    const dateDiv = document.createElement('div');
                    dateDiv.className = 'date-divider';
                    dateDiv.textContent = isToday(theme.effectiveTime) ? '今日' : dateStr;
                    themeList.appendChild(dateDiv);
                }
                
                const card = createThemeCard(theme);
                themeList.appendChild(card);

                if (index === 0) {
                    card.classList.add('active');
                    activeTheme = theme.sPlateCode;
                    showStockDetails(theme);
                }
            });
        }

        renderThemeList();
        
        // 添加导入股票到通达信的功能
        document.getElementById('collectStocksBtn').addEventListener('click', function(event) {
            event.preventDefault();
            const stockElements = document.querySelectorAll('.stock-item');
            const stockCodes = [];
            
            stockElements.forEach(element => {
                const code = element.dataset.code;
                if (!code) return;
                
                // 移除股票代码前缀（如sz、sh）
                const cleanCode = code.replace(/^(sz|sh)/, '');
                let formattedCode;
                
                // 根据股票代码前缀判断市场
                if (cleanCode.startsWith('6')) {
                    // 上海市场
                    formattedCode = '1#' + cleanCode;
                } else if (cleanCode.startsWith('0') || cleanCode.startsWith('3')) {
                    // 深圳市场
                    formattedCode = '0#' + cleanCode;
                } else if (cleanCode.startsWith('4') || cleanCode.startsWith('8') || cleanCode.startsWith('9')) {
                    // 其他市场
                    formattedCode = '2#' + cleanCode;
                } else {
                    return;
                }
                
                stockCodes.push(formattedCode);
            });
            
            if (stockCodes.length > 0) {
                const codeString = stockCodes.join('|');
                const url = 'http://www.treeid/AddToBlock_' + codeString;
                
                // 尝试复制到剪贴板
                navigator.clipboard.writeText(codeString).then(() => {
                    window.location.href = url;
                }).catch(err => {
                    // 备用复制方法
                    const textArea = document.createElement('textarea');
                    textArea.value = codeString;
                    document.body.appendChild(textArea);
                    textArea.select();
                    try {
                        document.execCommand('copy');
                        window.location.href = url;
                    } catch (error) {
                        console.error('复制失败:', error);
                    }
                    document.body.removeChild(textArea);
                });
            }
        });
        
        setInterval(renderThemeList, 1000000);
    </script>
</body>
</html>
